import GraphLayout from '@/components/graphLayout';
import ProCard from '@ant-design/pro-card';
import { useRequest } from '@umijs/hooks';
import Graphin from '@antv/graphin';
import { Card, List, Tabs } from 'antd';
import { useEffect, useState } from 'react';
import AvatarList from './components/avatarList';
import ControlPowerList from './components/controlPowerList';
import EquityGraph from './components/graph';
import EquityRelationNetworkGraph from '../../MultiQuery/components/graph';
import iconLoader from '@antv/graphin-icons';
import { Empty } from 'antd';

import { getRelationNetwork, getEquityList, getEquityStruct } from '@/services/zhirong/equity';

import DemoPie from './components/pie';
import RelationList from './components/RelationList';
import './style.css';
const { fontFamily } = iconLoader();
const icons = Graphin.registerFontFamily(iconLoader);

const ComputeFinalHolders = (network) => {
  const { nodes, edges } = network;
  const finalHolders = nodes?.map((node) => {
    return {
      ...node,
      inDegree: 0,
      outDegree: 0,
    };
  });
  edges?.forEach((edge) => {
    finalHolders.forEach((node) => {
      if (node.id === edge.source) {
        node.outDegree += 1;
      }
      if (node.id === edge.target) {
        node.inDegree += 1;
      }
    });
  });
  return finalHolders?.filter((node) => node.inDegree === 0);
};

const Penetration = ({ enterprise, setEnterprise, date }) => {
  console.log("21212", enterprise)
  const [holders, setHolders] = useState([]);
  // 存储控制权组件传来的信息
  const [controlData, setControlData] = useState();
  // 传给graph组件的参数，配合onChangePanel进行控制图的刷新
  const [network, setNetwork] = useState();
  const [controlHolders, setControlHolders] = useState([]);
  const [loading, setLoading] = useState(false);
  // true是股权网络的图，false是控制权的图
  const [isNetworkPanel, setPanelType] = useState(true);

  const [runRelationData, setRunRelationData] = useState({});
  const [equityList, setEquityList] = useState([]);
  const [equityStructPieData, setEquityStructPieData] = useState([]);


  const handleUpdateNetwork = (network) => {
    setEnterprise({ ...enterprise, network });
  };
  /*   const handleUpdateEnterprise = (enterprise)=>{
      setEnterprise({ ...enterprise })
    } */


  const { run: runRelation } = useRequest(getRelationNetwork, {
    manual: true,
    onSuccess: (result) => {
      const data = parseGraphData(result.data, enterprise.eid)
      console.log("45755674646", data);

      setRunRelationData(data)
    },
  });


  const { run: runGetFinalEquityList } = useRequest(getEquityList, {
    manual: true,
    onSuccess: (result) => {
      console.log("股权", result);

      setEquityList(result.data)
    },
  });

  const { run: runGetEquityStruct } = useRequest(getEquityStruct, {
    manual: true,
    onSuccess: (result) => {
      console.log("饼图", result);

      setEquityStructPieData(result.data)
    },
  });




  const parseGraphData = (data, centerID) => {
    const nodeParser = (node) => {
      return {
        id: node.id,
        style: {
          label: {
            value: node.name,
          },
          icon: {
            fontFamily,
            type: 'font',
            value: node.category === 'E' ? icons.company : icons.user,
            fill: centerID?.includes(node.id) ? 'red' : '#3da2ff',
            size: 23,
            fillOpacity: 0.8,
          },
          keyshape: {
            size: 32,
            fill: centerID?.includes(node.id) ? 'red' : '#3da2ff',
            stroke: centerID?.includes(node.id) ? 'red' : '#3da2ff',
            lineWidth: 3,
          },
        },
      };
    };
    const edgeParser = (edge) => {
      return {
        id: edge.id,
        source: edge.source,
        target: edge.target,
        style: {
          label: {
            value: edge.label,
            fill: '#838383',
          },
          keyshape: {
            stroke: '#999999',
            // lineWidth: 4,
          },
        },
      };
    };

    console.log('adadadad', data?.nodes)
    return {
      nodes: data?.nodes?.map(nodeParser),
      edges: data?.relations?.map(edgeParser),
    };
  };



  useEffect(() => {
    // console.log('enterprise changes>>>>>', enterprise, enterprise.network)
    const res = ComputeFinalHolders(enterprise.network || { node: [], edge: [] });
    if (res?.length != 0) {
      setHolders(res);
    }

    runRelation({
      centerId: enterprise.eid,

    });
    runGetFinalEquityList({
      centerId: enterprise.eid,
    });
    runGetEquityStruct({
      centerId: enterprise.eid,
    })

  }, [enterprise.network, network, enterprise]);

  const onChangePanel = (key) => {
    setPanelType(!isNetworkPanel);
    // console.log("key", key);
    if (key == '1') {
      setNetwork(undefined);
    } else if (key == '2') {
      setNetwork(controlData);
    }
  };
  const onClick = () => {
    setLoading(true);
    setTimeout(() => setLoading(false), 0);
  };

  const getControlPower = (props) => {
    console.log('拿到的控制权信息', props);
    if (props) {
      setControlData(props);
      setNetwork(props);
    }
  };

  const { TabPane } = Tabs;

  return (
    <>
      {<GraphLayout
        display={'none'}
        leftSpan={24}
        leftChildren={
          <ProCard style={{ borderRadius: '8px', height: '61vh' }} loading={loading}>
            {/* 防止graphin图标加载滞后 */}
            <div style={{ height: '0px', overflow: 'hidden' }}>
              <span
                style={{
                  fontFamily: 'graphin',
                  transform: 'scale(0)',
                  opacity: 0,
                  fontSize: '1px',
                }}
              >
                &#xe7ce;
              </span>
            </div>
            <Empty description="暂无数据" />
            {/* <EquityGraph
              height='30vh'
              eid={enterprise.eid}
              network={network}
              onNetworkChange={handleUpdateNetwork}
              date={date}
              holders={holders}
              refresh={onClick}
            /> */}
          </ProCard>
        }

      />
      }



      <GraphLayout
        display={'none'}
        leftSpan={13}
        rightSpan={11}
        rightChildren={
          <Tabs defaultActiveKey="1" centered tabBarGutter="8rem" style={{ marginTop: '60px' }}>
            <TabPane tab={<b >股权穿透图谱</b>} key="1">

              <ProCard style={{ borderRadius: '8px', height: '61vh' }} loading={loading}>
                {/* 防止graphin图标加载滞后 */}
                <div style={{ height: '0px', overflow: 'hidden' }}>
                  <span
                    style={{
                      fontFamily: 'graphin',
                      transform: 'scale(0)',
                      opacity: 0,
                      fontSize: '1px',
                    }}
                  >
                    &#xe7ce;
                  </span>
                </div>
                {enterprise.eid != '' ? <EquityGraph
                  height='30vh'
                  eid={enterprise.eid}
                  network={network}
                  onNetworkChange={handleUpdateNetwork}
                  date={date}
                  holders={holders}
                  refresh={onClick}
                /> : <Empty description="暂无数据" />
                }

              </ProCard>
            </TabPane>
            <TabPane tab={<b >股东关系图谱</b>} key="2">
              <ProCard style={{ borderRadius: '8px', height: '61vh' }} loading={loading}>
                {/* 防止graphin图标加载滞后 */}
                <div style={{ height: '0px', overflow: 'hidden' }}>
                  <span
                    style={{
                      fontFamily: 'graphin',
                      transform: 'scale(0)',
                      opacity: 0,
                      fontSize: '1px',
                    }}
                  >
                    &#xe7ce;
                  </span>
                </div>
                {/* <EquityGraph
                  data={this.state.data}
                  expander={this.state.upd}
                  setFocusNodeId={(focusNodeId) => this.setState({ ...this.state, focusNodeId })}
                  refresh={this.refresh}  //刷新函数
                ></EquityGraph> */}
                <EquityRelationNetworkGraph
                  height='30vh'
                  data={runRelationData}
                  setFocusNodeId={''}

                // network={network}
                // onNetworkChange={handleUpdateNetwork}
                // date={date}
                // holders={holders}
                // refresh={onClick}
                // type='1'
                />
              </ProCard>
            </TabPane>
            <TabPane tab={<b >股权结构分析</b>} key="3">
              {/* 饼状图 */}
              <ProCard
                style={{ borderRadius: '8px', height: '61vh' }}
                loading={loading}
              >


                <List
                  pagination={{
                    showSizeChanger: false,
                    pageSize: 1,
                  }}
                  dataSource={[
                    <DemoPie
                      data={equityStructPieData}
                    />
                    ,
                    ...(enterprise.network?.plots || []),
                  ]}
                  renderItem={(plot) =>
                    plot.type === DemoPie ? (
                      <Card>{plot}</Card>
                    ) : (
                      <Card title={plot.title} style={{ minHeight: '20em' }}>
                        <img
                          src={`data:image/png;base64,${plot.img64}`}
                          style={{ maxWidth: '90%', maxHeight: '90' }}
                        />
                      </Card>
                    )
                  }
                />
              </ProCard>
            </TabPane>
          </Tabs>


        }
        leftChildren={
          <>
            <ProCard style={{ borderRadius: '8px', height: '61vh', marginTop: '120px' }} bodyStyle={{ padding: '0' }} loading={loading}>
              <Tabs defaultActiveKey="1" centered tabBarGutter="8rem" onChange={onChangePanel} >
                {/* 股权穿透信息 */}
                <TabPane tab={<b style={{ fontSize: '18px' }}>最终股权穿透查询</b>} key="1">
                  {/*    <p>
              <b>股权网络层数: </b>
              {enterprise.network?.stat?.[0].value}
            </p>
            <p>
              <b>计算耗时:</b> {`${enterprise.network?.stat?.[1].value.toFixed(3) ?? ''}`}
            </p> */}
                  <ProCard
                    bodyStyle={{ padding: '0' }}
                    direction="column"
                    style={{ height: '54vh', overflowY: 'auto', overflowX: 'hidden' }}
                    className="content"
                  >
                    {/* 最终股东 */}
                    <ProCard title={<b style={{ fontSize: '18px' }}>股东信息</b>}>
                      <AvatarList holders={equityList} loading={loading} />
                    </ProCard>

                    {/* <ProCard title={<b style={{ fontSize: '18px' }}>股东关系图谱</b>}>
                      <AvatarList holders={holders} loading={loading} />
                    </ProCard> */}

                  </ProCard>
                </TabPane>
                {/* 控制权信息 */}
                {/* <TabPane tab={<b style={{ fontSize: '18px' }}>控制权信息</b>} key="2">
                  <ProCard
                    bodyStyle={{ padding: '0' }}
                    direction="column"
                    style={{ height: '90vh', overflow: 'auto', overflowX: false }}
                    className="content"
                  > */}
                {/* 疑似实际控制人  */}
                {/* <ProCard title={<b style={{ fontSize: '18px' }}>疑似实际控制人</b>}>
                      <ControlPowerList
                        holders={holders}
                        getControlPower={getControlPower}
                        enterprise={enterprise}
                      />
                    </ProCard> */}
                {/* 外部关系 */}
                {/* <ProCard title={<b style={{ fontSize: '18px' }}>外部关系</b>}>
                      <RelationList
                        getControlPower={getControlPower}
                        enterprise={enterprise}
                        controlData={controlData}
                      />
                    </ProCard>
                  </ProCard>
                </TabPane> */}
              </Tabs>
            </ProCard>
          </>
        }
      />
    </>

    /* <RankList isShow={!Boolean(enterprise.eid)} onClick={handleClickRank} /> */
  );
};

export default Penetration;
